﻿using System.Web.Mvc;
using System.Web.Routing;
using easyccms.WebUI.Code;

namespace easyccms.WebUI
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    /// <summary>
    /// Mvc application start up.
    /// </summary>
    public class MvcApplication : System.Web.HttpApplication
    {
        /// <summary>
        /// Application_s the start.
        /// </summary>
        protected void Application_Start()
        {
            if (!this.IsApplicationOnline())
            {
                System.Web.HttpContext.Current.Response.Redirect(ApplicationOfflinePage(), true);
            }
            else
            {
                AreaRegistration.RegisterAllAreas();
                log4net.Config.XmlConfigurator.Configure();
                RegisterRoutes(RouteTable.Routes);
            }

            // This solution does not work for present
            // ControllerBuilder.Current.SetControllerFactory(typeof(DiControllerFactory)); 
        }

        /// <summary>
        /// Registers the routes.
        /// </summary>
        /// <param name="routes">The routes.</param>
        private static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default",
                "{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = UrlParameter.Optional });
        }

        /// <summary>
        /// Determines whether [is application online].
        /// </summary>
        /// <returns>
        ///   <c>true</c> if [is application online]; otherwise, <c>false</c>.
        /// </returns>
        private bool IsApplicationOnline()
        {

            return ApplicationSettings().Online;
        }

        /// <summary>
        /// Applications the settings.
        /// </summary>
        /// <returns>Location where offline page is located.</returns>
        private static ApplicationSettings ApplicationSettings()
        {
            ApplicationSettings settings = new ApplicationSettings();
            return settings;
        }

        /// <summary>
        /// Applications the offline page.
        /// </summary>
        /// <returns>Determines whether the website is offline.</returns>
        private string ApplicationOfflinePage()
        {
            return ApplicationSettings().OfflinePage;
        }
    }
}